<script setup>
  import { ref, watch } from 'vue'
  import './assets/style.css'
  import Header from './components/Header.vue';
  import Main from './components/Main.vue';
  import Footer from './components/Footer.vue';
  // 若是本地存在数据，则取用本地数据；否则使用预置数据
  const todoList = ref(JSON.parse(localStorage.getItem(TODO_LIST_KEY)) || [
    { id: 321, name: '学Vue组件通信', finished: false },
    { id: 127, name: '打王者', finished: true },
    { id: 666, name: '跑步1⼩时', finished: false }
  ])
  // 数据持久化存储-键
  const TODO_LIST_KEY = "todo-list-key"

  // 数据持久化
  watch(todoList, () => {
    // 直接存储至本地
    localStorage.setItem(TODO_LIST_KEY, JSON.stringify(todoList.value))
  }, {
    deep: true
  })

  // 修改任务的完成状态
  const modifyStatus = (i) => {
    // 每个任务状态都默认为false，而checkbox也默认为false，因此每次点击取反即可
    todoList.value[i].finished = !todoList.value[i].finished
  }

  // 新增单个待办事项
  const addTodoTask = (todoTaskName) => {
    todoList.value.push({
      id: Date.now(),
      name: todoTaskName,
      finished: false
    })
  }

  // 删除单个待办事项
  const delTodoTask = (i) => {
    todoList.value.splice(i, 1)
  }

  // 删除所有已完成的事项
  const delCompleted = () => {
    todoList.value = todoList.value.filter((item) => !item.finished)
  } 

</script>
<template>
  <section class="todoapp">
    <Header
    @add="addTodoTask">
    </Header>
    
    <Main 
    :list="todoList"
    @modify="modifyStatus"
    @del="delTodoTask">
    </Main>

    <Footer 
    :list="todoList"
    @del_completed_task="delCompleted">
    </Footer>
  </section>
</template>